/**
 * token
 */

import jwt from 'jwt-simple';
import { TOKEN_KEY } from '../../server.config';
import { AuthError } from '../../utils/classModal';
import db from '../../utils/dbconf';
const TABLE_NAME = 'TOOL_TOKEN';

export default {
	// 获取服务端cookie
	getToken: (req) => {
		return req && req.headers['pakchoi-token'];
	},
	// 检查token
	async check(token) {
		if (!token) throw new AuthError();
		//解密获取的token
		let decoded = jwt.decode(token, TOKEN_KEY);
		//校验有效期
		if (!decoded || !decoded.exp || decoded.exp <= Date.now()) throw new AuthError('登录状态已过期');
		const ishave = await db.table(TABLE_NAME).where({ u_id: decoded.u_id, token }).count('id');
		if (!ishave) throw new AuthError('登录状态已过期');
		return decoded;
	},
	// 创建token
	async create(obj) {
		obj.exp = Date.now() + 1000 * 60 * 60 * 24 * 3; // * 999;
		const { u_id } = obj;
		const token = jwt.encode(obj, TOKEN_KEY);
		const hastoken = await db.table(TABLE_NAME).where({ u_id }).count('id');
		if (hastoken) await db.table(TABLE_NAME).where({ u_id }).update({ token });
		else await db.table(TABLE_NAME).add({ u_id, token });
		return token;
	},
	// 清除token
	async clearToken(u_id) {
		await db.table(TABLE_NAME).where({ u_id }).delete();
	},
};
